package com.google.code.sysarch.v3.pre;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.imageio.ImageIO;

/**
 * This singleton instance stores and manages all Sprites.
 * @author Fabian Nicolay
 */
public class SpritePool {

	private static SpritePool singleton = new SpritePool();
	private HashMap<String,Sprite> sprites = new HashMap<String,Sprite>();
	
	/** 
	 * Prevents of creating multiple instances of SpritePool. 
	 * The get method must be used to get a reference to the single instance.
	 */
	private SpritePool() { } 
	
	/** 
	 * Returns the singleton instance of SpritePool
	 * @return the singleton instance of SpritePool
	 */
	public static SpritePool get() {
		return singleton;
	}
	
	/**
	 * Returns a peculiar Sprite from the SpritePool (specfied by its filename)
	 * Creates this Sprite first, if necessary
	 * @param filename the filename of the image
	 * @return the Sprite
	 */
	public Sprite getSprite(String filename) {
		if (sprites.get(filename) != null) {
			return sprites.get(filename);
		}
		
		
		BufferedImage srcImage = null;
		try {
			srcImage = ImageIO.read(new File(filename));
		} catch (IOException e) {
			Util.printMessage("Can't load file \"" + filename + "\"",Util.MTYPE_ERROR);
		} 
		
		GraphicsConfiguration gc = 
			GraphicsEnvironment.getLocalGraphicsEnvironment()
				.getDefaultScreenDevice().getDefaultConfiguration();
		Image image = gc.createCompatibleImage(srcImage.getWidth(),
				srcImage.getHeight(),
				Transparency.BITMASK);
		image.getGraphics().drawImage(srcImage,0,0,null);
		Sprite sprite = new Sprite(image);
		sprites.put(filename,sprite);
		
		return sprite;
		
	} 
}
